package com.hcc.gateway.app.config;

import com.hcc.gateway.app.constant.HccGatewayAppConstant;
import com.hcc.gateway.common.utils.JsonUtils;
import com.hcc.gateway.domain.resp.GatewayResp;
import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.context.ReqContext;
import com.hcc.gateway.netty.context.RespContext;
import com.hcc.gateway.netty.exception.GatewayExceptionHandler;
import com.hcc.gateway.netty.support.ByteBufUtils;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * HccGatewayGlobalExceptionHandler
 *
 * @author shengjun.hu
 * @date 2021/12/27
 */
@Slf4j
@Component
public class HccGatewayGlobalExceptionHandler implements GatewayExceptionHandler {

    @SneakyThrows
    @Override
    public void handle(GatewayExchange exchange, Throwable t) {
        ReqContext reqContext = exchange.getReqContext();
        RespContext respContext = exchange.getRespContext();

        String traceId = exchange.getAttributeByName(HccGatewayAppConstant.HCC_TRACE_ID, String.class);

        log.error(String.format("请求地址：%s，traceId: [%s]，异常！", reqContext.getUri(), traceId),  t);

        GatewayResp<?> resp = new GatewayResp<>();
        resp.setTraceId(traceId);
        resp.setCode("GW601");
        resp.setSuccess(false);
        resp.setTimestamp(System.currentTimeMillis());
        resp.setMsg(t.getMessage());

        if (respContext.getHttpStatus() == null) {
            respContext.setHttpStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        respContext.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");
        respContext.setBody(ByteBufUtils.writeStringToByteBuf(JsonUtils.writeValueAsString(resp)));
    }

}
